<?php

/**
 * +------------------------------------------------------------------------------
 * 活动
 * +------------------------------------------------------------------------------
 */
class ActivityAction extends CommonAction
{

    /**
     * 活动表单页渲染
     */
    public function add()
    {
        $this->getUnit();
        $this->getActivity();
        $this->display();
    }

    /**
     *单个修改渲染edit页面
     */
    public function edit()
    {
        $model = $this->findModel();
        /** @$model Activity */
        $this->getUnit($model->start_date, $model->end_date);
        $this->getActivity();
        $this->assign('vo', $model->toArray());
        $cities = array_column(M('wx_area')->where(['parent_name' => $model->allow_province, 'level' =>2])->findAll(),'name');
        $cities['0'] = '请选择城市';
        $this->assign('cities', $cities);
        $this->display();
    }

    public function save()
    {
        if (!empty($_POST)) {
            $model = $this->findModel();
            $this->_save($model);
        }
    }

    protected function _save(ActivityModel $model)
    {

        //验证数据
        if (!$model->create()) {
            $this->error($model->error);
            exit();
        }
        //转换时间戳
        $model->unix($_POST);

        if ($_POST['allow_city'] == '请选择城市') {
            $model->allow_city = '';
        }
        if ($_POST['allow_province'] == '请选择省份') {
            $model->allow_province = '';
        }
        if ($model->save() !== false) {
            $this->redirect('index');
        } else {
            $this->error($model->error);
            exit();
        }


    }

    public function getUnit($start_date = null, $end_date = null)
    {
        import("@.ORG.form");
        $form = new form();
        $start_date = $start_date ?: time();
        $end_date = $end_date ?: time();
        $time = date("Y-m-d H:i", time());
        $start_date = $form->date("start_date", date("Y-m-d H:i", $start_date), true);
        $end_date = $form->date("end_date", date("Y-m-d H:i", $end_date), true);
        $this->assign("start_date", $start_date);
        $this->assign("end_date", $end_date);
    }

    /**
     * 输出json数据
     */
    public function city()
    {
        $province = $_POST['province'];
        $cities = array_column(D('wx_area')->where(['parent_name' => $province, 'level' => 2])->select(), 'name');
        $cities['0'] = '请选择城市';
        print_r(self::json($cities));
    }


    /**
     * @param $str
     * @return mixedfan
     * 数据格式化为json字符串
     */
    public static function json($str)
    {
        $json = json_encode($str);
        return preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $json);
    }


    /**
     * 获取城市
     */
    public function getActivity()
    {
        $model = M('wx_area');
        $province = $model->where(['level' => 1])->select();
        $province = array_column($province, 'name');
        $this->assign('province', $province);
    }

    /**
     * 海报拖动效果
     */
    public function poster()
    {
        $model = $this->findModel();
        $model->backgroud_path = $model->backgroud_path ?: '';
        $this->assign('vo', $model->toArray());
        $this->assign('root', PIC_ROOT);
        $this->display();
    }

    /**
     * @return ActivityModel
     */
    protected function findModel()
    {
        $model = D('Activity');
        $idParam = $model->getPk();
        $id = $_REQUEST[$idParam] ?: null;
        if ($id) {
            $model->find($id);
        }
        return $model;
    }

    /**
     * 保存图片
     */
    public function savePost()
    {
        $activity_id = $_GET['activity_id'];

        if ($_FILES['backgroud_path']['name']) {
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize = 3145728;// 设置附件上传大小
            $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->saveRule = 'uniqid';

            $subPath = 'public/upload/images/' . date('Ym') . '/' . date('d') . '/';
            $imageRoot = RES_ROOT . $subPath;
            mkdir($imageRoot, 0777, true);

            $upload->savePath = $imageRoot; // 设置附件上传（子）目录
            // 上传文件
            $upload->upload();
            $info = $upload->getUploadFileInfo();
            $this->backgroud_path = $subPath . $info[0]['savename'];
        }

    }

    public function uploadImg()
    {
        try {
            if ($_FILES["AidImg"]["size"] != 0) {
                $upload = new UploadFile();// 实例化上传类
                $upload->maxSize = 3145728;// 设置附件上传大小
                $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->saveRule = 'uniqid';

                $subPath = 'public/upload/images/' . date('Ym') . '/' . date('d') . '/';
                $imageRoot = RES_ROOT . $subPath;
                mkdir($imageRoot, 0777, true);

                $upload->savePath = $imageRoot; // 设置附件上传（子）目录
                // 上传文件
                $upload->upload();
                $info = $upload->getUploadFileInfo();
                $imgUrl = $subPath . $info[0]['savename'];
            }
        } catch (Exception $e) {
            echo "<script>parent.callback('图片上传失败',false)</script>";
            return;
        }
        echo "<script>parent.callback('$imgUrl',true)</script>";
    }


}

?>